package com.panku.core.controller;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.panku.annocation.myRequestParam;
import com.panku.core.entity.ClassBean;

public class DispatcherController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		//存放控制器返回的结果,即要跳转的页面
		String resVal="";
		String path=getPath(req.getServletPath());
		Map<String, ClassBean> pathList=(Map<String, ClassBean>)req.getServletContext().getAttribute("pathList");
		ClassBean curBean=pathList.get(path);
		if (curBean!=null) {
			try {
				Class<?> clazz=curBean.getClazz();
				Method method=curBean.getMethod();
				Parameter[] params=method.getParameters();
				Object[] paramsArr=new Object[params.length];
				for (int i = 0; i < params.length; i++) {
					if (params[i].isAnnotationPresent(myRequestParam.class)) {
						myRequestParam paramAnno = params[i].getAnnotation(myRequestParam.class);
						paramsArr[i]=req.getParameter(paramAnno.value());
					}else{
						String typeName = params[i].getType().getTypeName();
						System.out.println(typeName);
						if (typeName.equals("javax.servlet.http.HttpServletRequest")) {
							paramsArr[i]=req;
						}else if(typeName.equals("javax.servlet.http.HttpServletResponse")){
							paramsArr[i]=resp;
						}else{
							throw new Exception("参数没有绑定注解~!");
						}
						
					}
					
					
					
				}
				
				resVal=method.invoke(clazz.newInstance(), paramsArr).toString();
				req.getRequestDispatcher("/"+resVal).forward(req, resp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				throw new Exception("没有找到指定的请求路径~!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
	}

	public String getPath(String sourceStr){
		if (sourceStr!=null&&sourceStr.length()>0) {
			return sourceStr.split("\\.")[0];
		}
		return null;
	}
	
}
